// createRouter          用于创建路由的函数
// createWebHashHistory  用于创建哈希路由的函数
import { createRouter, createWebHashHistory } from 'vue-router'

import Layout from '@/views/Layout.vue'
import Home from '@/views/home/index.vue'
import CategoryIndex from '@/views/category/index.vue'
import CategorySub from '@/views/category/sub.vue'
import store from '@/store'

// 配置路由，，路径和组件的映射关系
const routes = [
  {
    // Layout布局组件(公共头部和底部)
    path: '/',
    component: Layout,
    // 需要用到公共 Layout 的页面
    children: [
      { path: '', component: Home }, // 首页组件
      { path: 'category/:id', component: CategoryIndex }, // 一级分类页
      { path: 'category/sub/:id', component: CategorySub }, // 二级分类页
      { path: 'product/:id', component: () => import('@/views/goods/index') },
      { path: 'cart', component: () => import('@/views/cart/index.vue') },
      { path: '/member/checkout', component: () => import('@/views/member/pay/checkout') }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/login/callback',
    component: () => import('@/views/login/callback')
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior () {
    return { left: 0, top: 0 }
  }
})
// 前置导航守卫

router.beforeEach((to, from, next) => {
  // 用户信息
  const { token } = store.state.user.profile
  // 跳转去member开头的地址却没有登录
  if (to.path.startsWith('/member') && !token) {
    next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})

// 导出路由实例
export default router
